package com.yiyuan.system.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.yiyuan.common.base.BaseDao;
import com.yiyuan.system.dao.IEmpDao;
import com.yiyuan.system.model.Employee;

@Repository("empDao")
public class EmpDaoHbImpl extends BaseDao implements IEmpDao {
	public void add(Employee employee) {
		this.getHibernateTemplate().save(employee);
	}

	@SuppressWarnings("unchecked")
	public List<Employee> findList(int startIndex, int endIndex,
			String empName, Integer deptId) {
		Session session = this.getSession();
		StringBuffer sbsql = new StringBuffer(100);
		boolean empFlag = false;
		boolean deptFlag = false;
		if (empName != null && !empName.equals("")) {
			empFlag = true;
		}
		if (deptId != null) {
			deptFlag = true;
		}
		sbsql.append("from Employee ");
		if (empFlag) {
			sbsql.append(" where empName like '%'||:empName||'%' ");
			if (deptFlag) {
				sbsql.append(" and deptId=:deptId");
			}
		} else {
			if (deptFlag) {
				sbsql.append(" where deptId=:deptId");
			}
		}

		Query query = session.createQuery(sbsql.toString());
		if (empFlag) {
			query.setString("empName", empName);

		}
		if (deptFlag) {
			query.setInteger("deptId", deptId);
		}

		query.setFirstResult(startIndex - 1);
		query.setMaxResults(endIndex);
		List<Employee> list = query.list();
		return list;
	}

	public int getPageCount(String empName, Integer deptId) {
		Session session = this.getSession();
		StringBuffer sbsql = new StringBuffer(100);
		boolean empFlag = false;
		boolean deptFlag = false;
		if (empName != null && !empName.equals("")) {
			empFlag = true;
		}
		if (deptId != null) {
			deptFlag = true;
		}
		sbsql.append("select count(*) from Employee ");
		if (empFlag) {
			sbsql.append(" where empName like '%'||:empName||'%' ");
			if (deptFlag) {
				sbsql.append(" and deptId=:deptId");
			}
		} else {
			if (deptFlag) {
				sbsql.append(" where deptId=:deptId");
			}
		}
		Query query = session.createQuery(sbsql.toString());
		if (empFlag) {
			query.setString("empName", empName);

		}
		if (deptFlag) {
			query.setInteger("deptId", deptId);
		}
		int count = Integer.parseInt(query.uniqueResult().toString());
		return count;
	}

	public void update(Employee employee) {
		this.getHibernateTemplate().update(employee);
	}

	public Employee get(Integer empId) {
		return (Employee) this.getHibernateTemplate()
				.get(Employee.class, empId);
	}

	public void delete(Employee employee) {
		this.getHibernateTemplate().delete(employee);
	}

	@SuppressWarnings("unchecked")
	public List<Employee> findListByDeptId(Integer deptId) {
		Session session = this.getSession();
		Query query = session.createQuery("from Employee where deptId=:deptId");
		query.setInteger("deptId", deptId);
		List<Employee> list = query.list();
		return list;
	}
}
